package com.zg.http;

import com.btzh.mis.util.SingletonObject;
import org.apache.commons.lang3.StringUtils;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 通过Jersey的响应过滤器,统一封装响应内容,提供http响应码,业务状态和数据结果的封装
 * @see ResponseBean
 * @author 王利东
 */
@Provider
public class JerseyResponseFilter implements ContainerResponseFilter {

	@Override
	public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
        Object entity = responseContext.getEntity();
//		if (null != entity && entity instanceof Viewable) {
//			return;
//		}

		Integer code = ResponseBean._getCode();
		if (null == code) {
			code = responseContext.getStatus() == Response.Status.NO_CONTENT.getStatusCode() ? Response.Status.OK.getStatusCode() : responseContext.getStatus();
		}
		
		if (entity instanceof BareResponseBean) {
			BareResponseBean bean = (BareResponseBean)entity;
			responseContext.setEntity(bean.getEntity(), null, bean.getMediaType());
			responseContext.setStatus(code);
		} else {
			String status = ResponseBean._getStatus();
			if (StringUtils.isBlank(status)) {
				status = "yes";
			}
			
			ResponseBean.set(code, status, responseContext.getEntity());
			
			Map<String, Object> mapEntity = ResponseBean.getEntity();
			for (Iterator<Entry<String, Object>> iterator = mapEntity.entrySet().iterator(); iterator.hasNext();) {
				if (null == iterator.next().getValue()) {
					iterator.remove();
				}
			}
			responseContext.setEntity(SingletonObject.objectMapper.writeValueAsString(mapEntity), null, MediaType.APPLICATION_JSON_TYPE);
			responseContext.setStatus(code);
		}
		
		ResponseBean.getEntity().clear();

		//TODO 项目上线后删除跨域设置
        //跨域问题
        responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");

        //允许的Header值，不支持通配符
        responseContext.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
        responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");

        //即使只用其中几种，header和options是不能删除的，因为浏览器通过options请求来获取服务的跨域策略
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");

        //CORS策略的缓存时间
        responseContext.getHeaders().add("Access-Control-Max-Age", "1209600");
	}
}